<template>
  <a-drawer
    :title="title"
    :placement="placement"
    :closable="true"
    :destroyOnClose="true"
    width="100%"
    height="100%"
    @close="onClose"
    :zIndex="10001"
    :visible="visible"
    wrapClassName="scoped-drawer"
  >
    <div class="map-wrap">
      <div class="map-container" id="container"></div>
      <div class="submit-btn">
        <a-row :gutter="20">
          <a-col :span="4">
            <a-select
              show-search
              v-model="address"
              style="width: 200px"
              placeholder="请输入要搜索的区域名称"
              :default-active-first-option="false"
              :show-arrow="false"
              :filter-option="false"
              :not-found-content="null"
              @search="inputSearch"
              @change="inputChange"
            >
              <a-select-option v-for="(item, index) in suggestionList" :key="index" :value="item.id"
                >{{ item.title }}-{{ item.address }}</a-select-option
              >
            </a-select>
          </a-col>
          <a-col :span="8" offset="5" v-if="renderType === 'boundary'">
            <div>{{ borderStr }}</div>
            <a-button @click="saveBorderLine" type="primary">保存边界</a-button>
          </a-col>
          <a-col :span="8" offset="5" v-if="renderType === 'point'">
            <a-input placeholder style="width: 200px" v-model="latLng" />
            <a-button @click="confimClick" type="primary">确认选择</a-button>
          </a-col>
        </a-row>
      </div>
    </div>
  </a-drawer>
</template>

<script>
import { getAction } from '@/api/manage'
export default {
  name: 'Index',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },

    // 类型  用来判断是 选择经纬度，还是选择 边界信息
    // point | boundary
    renderType: {
      type: String,
      default: '',
    },
  },
  computed: {
    title() {
      return this.renderType === 'point' ? '坐标拾取' : '边界绘制'
    },
  },
  data() {
    return {
      placement: 'top',
      address: '',
      borderLine: false,

      latLng: '',
      suggestionList: [],

      borderStr: '',
      polyEditor: null,
    }
  },
  watch: {
    visible: function (newValue) {
      if (newValue) {
        this.$nextTick(() => {
          this.init()

          // 如果当前 是绘制边界的话，则
          if (this.renderType === 'boundary') {
            this.getFilteredPoliceJurisdictionList()
          }
          // 判断 如果有边界信息
          if (this.borderLine && this.borderStr) {
            const paths = this.borderStr.split(';').map((item) => {
              const [lng, lat] = item.split(',') // 缓存分割结果
              return new TMap.LatLng(lat, lng)
            })
            this.renderSearchArea(paths)
            this.polyEditor.enable()
            this.fitMapBounds(paths)
          }
        })
      }
    },
  },
  mounted() {},
  methods: {
    // * 获取辖区列表
    async getFilteredPoliceJurisdictionList(policeAgencyId) {
      const { result: policeJurisdictionList } = await getAction(
        '/police/jurisdiction/find_police_agency_jurisdiction_list',
        {
          policeAgencyId,
          pigeSize: 99999,
        }
      )
      const filteredPoliceJurisdictionList = policeJurisdictionList.filter((item) => !!item.areaPosition)

      filteredPoliceJurisdictionList.forEach((item) => {
        // 要跳过当前的这个区域
        if (this.borderStr !== item.areaPosition) {
          this.drawPolygon(item.areaPosition.split(';'), item.positionColour, item.jurisdictionName, item.lat, item.lng)
        }
      })
    },

    drawPolygon(pPath, pColor, jName, jLat, jLng) {
      let path = []
      pPath.forEach((item) => {
        const [lng, lat] = item.split(',') // 缓存分割结果
        try {
          let r = new TMap.LatLng(lat, lng)
          if (r.lng) {
            path.push(r)
          }
        } catch (error) {}
      })
      if (!path.length) return

      let color = pColor.replace(')', ',.3)')
      // 初始化polygon
      this.polygon = new TMap.MultiPolygon({
        // id: 'polygon-layer', // 图层id
        map: this.map, // 显示多边形图层的底图
        styles: {
          // 多边形的相关样式
          polygon: new TMap.PolygonStyle({
            color: color, // 面填充色
            showBorder: true, // 是否显示拔起面的边线
            // extrudeHeight: 3000, //多边形拔起高度
            borderColor: pColor, //边线颜色
          }),
        },
        geometries: [
          {
            id: 'polygon', // 多边形图形数据的标志信息
            styleId: 'polygon', // 样式id
            paths: path, // 多边形的位置信息
          },
        ],
      })

      this.label = new TMap.MultiLabel({
        // id: 'label-layer',
        map: this.map,
        styles: {
          label: new TMap.LabelStyle({
            color: '#3777FF', //颜色属性
            size: 20, //文字大小属性
            offset: { x: 0, y: 0 }, //文字偏移属性单位为像素
            angle: 0, //文字旋转属性
            alignment: 'center', //文字水平对齐属性
            verticalAlignment: 'middle', //文字垂直对齐属性
          }),
        },
        geometries: [
          {
            id: 'label', //点图形数据的标志信息
            styleId: 'label', //样式id
            position: new TMap.LatLng(jLat, jLng), //标注点位置
            content: jName, //标注文本
            properties: {
              //标注点的属性数据
              title: 'label',
            },
          },
        ],
      })
    },

    onClose() {
      this.latLng = ''
      this.address = ''
      this.borderStr = ''
      this.visible = false
      this.$emit('update:visible', false)
    },

    init() {
      let { policeAgencyLat, policeAgencyLng } = JSON.parse(localStorage.getItem('pro__Login_Userinfo')).value
      this.map = new TMap.Map(document.getElementById('container'), {
        center: new TMap.LatLng(policeAgencyLat, policeAgencyLng), // 西安
        zoom: 14,
        minZoom: 6,
        maxZoom: 20,
        doubleClickZoom: false,
        showControl: false,
      })

      this.map.on('click', (event) => {
        let {
          latLng: { lat, lng },
        } = event
        this.latLng = `${lng},${lat}`
      })
      this.suggest = new TMap.service.Suggestion({ pageSize: 10 })
    },

    async inputSearch(val) {
      console.log('inputSearch')
      let { data } = await this.suggest.getSuggestions({ keyword: val, location: this.map.getCenter() })
      this.suggestionList = data
    },

    inputChange() {
      let { lat, lng } = this.suggestionList.find((item) => item.id === this.address).location
      this.map.setCenter(new TMap.LatLng(lat, lng))
      console.log(this.borderLine)
      if (this.renderType === 'boundary') {
        const paths = [
          new TMap.LatLng(lat, lng),
          new TMap.LatLng(lat + 0.011, lng + 0.011),
          new TMap.LatLng(lat - 0.011, lng + 0.011),
        ]
        this.renderSearchArea(paths)
      }
    },

    // 渲染图层
    renderSearchArea(paths = []) {
      // 初始化几何图形及编辑器
      this.polyEditor = new TMap.tools.GeometryEditor({
        map: this.map, // 编辑器绑定的地图对象
        overlayList: [
          // 可编辑图层
          {
            overlay: new TMap.MultiPolygon({
              map: this.map,
              styles: {
                highlight: new TMap.PolygonStyle({
                  color: 'rgba(255, 255, 0, 0.6)',
                }),
              },
              geometries: [
                {
                  paths,
                },
              ],
            }),
            id: 'polygon',
            selectedStyleId: 'highlight',
          },
        ],
        actionMode: TMap.tools.constants.EDITOR_ACTION.INTERACT, // 编辑器的工作模式
        activeOverlayId: 'polygon', // 激活图层
        selectable: true, // 开启点选功能
        snappable: true, // 开启吸附
      })

      this.polyEditor.on('adjust_complete', (event) => {
        let { paths } = event
        let arr = []
        paths.forEach((item) => {
          arr.push(`${item.lng},${item.lat}`)
        })
        this.borderStr = arr.join(';')
      })
    },
    // 自适应点标记
    fitMapBounds(paths = []) {
      var latlngBounds = new TMap.LatLngBounds()
      for (var i = 0; i < paths.length; i++) {
        latlngBounds.extend(paths[i])
      }
      this.map.fitBounds(latlngBounds, {
        padding: 200,
      })
    },
    confimClick() {
      if (this.latLng === '') {
        this.$message.error('请点击目标地点获取坐标后再保存！！！')
        return
      }
      this.$emit('getLatLong', this.latLng.split(','))
      this.$emit('update:visible', false)
    },

    saveBorderLine() {
      if (this.borderStr === '') {
        this.$message.error('请编辑边界后再保存！！！')
        return
      }
      this.$emit('border', this.borderStr)
      this.borderLine = false
      this.borderStr = ''
      this.$emit('update:visible', false)
    },
  },
}
</script>

<style scoped lang="less">
.map-wrap {
  position: relative;

  .submit-btn {
    position: absolute;
    top: 0;
    width: 100%;
  }
}
</style>

<style>
.ant-select-dropdown {
  z-index: 99999;
}
.ant-message {
  z-index: 999999;
}
</style>
